package com.syf.kit.soa.core.balance.spi;

import com.syf.kit.soa.core.SOARegionInfo;
import com.syf.kit.soa.core.balance.SyfRpcBalance;

import java.util.List;
import java.util.Random;

public class WeightRpcBalance implements SyfRpcBalance {

    @Override
    public SOARegionInfo balance(List<SOARegionInfo> soaRegionInfos) {
        int totalWeight = 0;
        for (SOARegionInfo soaRegionInfo : soaRegionInfos) {
            totalWeight += soaRegionInfo.getWeight();
        }

        Random random = new Random();
        int randomNum = random.nextInt(totalWeight);

        int currentWeight = 0;
        for (SOARegionInfo soaRegionInfo : soaRegionInfos) {
            currentWeight += soaRegionInfo.getWeight();
            if (currentWeight >= randomNum) {
                return soaRegionInfo;
            }
        }

        return soaRegionInfos.get(0);
    }
}
